import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from 'nestjs-config';
import * as path from 'path';
import { UsersModule } from './users/users.module';
import { PostsModule } from './posts/posts.module';
import { RoleModule } from './role/role.module';
import { RedisUtilsModule } from './modules/redis-utils/redis-utils.module';

// 配置加载配置文件
const Config = ConfigModule.load(
  path.resolve(__dirname, 'config', '**/!(*.d).{ts,js}'),
  { modifyConfigName: name => name.replace('.config', '') },
);

// 配置mysql连接
// 必须配置 config/database.config.ts文件，这里才能识别
const typeOrmModule = TypeOrmModule.forRootAsync({
  useFactory: async (config: ConfigService) => {
    const configData = {
      type: config.get('database.type'),
      host: config.get('database.host'),
      port: config.get('database.port'),
      username: config.get('database.username'),
      password: config.get('database.password'),
      database: config.get('database.database'),
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      logging: config.get('database.logging'),
      synchronize: true, // 同步到数据库
    };
    console.log('----configData-----', configData);
    return configData;
  },
  inject: [ConfigService],
});

@Module({
  imports: [Config, typeOrmModule, UsersModule, PostsModule, RoleModule, RedisUtilsModule],
  controllers: [],
  providers: [],
})
export class AppModule {}
